from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from typing import List, Optional
from app.db.database import get_db
from app.core.security import check_admin_permission, get_current_user
from app.core.exceptions import DataNotFoundError, DuplicatePublishError
from app.models.post import Activity, PostType
from app.models.form import Form, FormSubmission
from app.schemas.post import ActivityCreate, Activity as ActivitySchema, PostList
from app.schemas.form import FormCreate, FormSubmissionCreate
from app.schemas.user import TokenData
from math import ceil

router = APIRouter(prefix="/post/activity", tags=["活动"])

@router.get("/suggestion", response_model=PostList)
async def get_activity_suggestions(
    db: AsyncSession = Depends(get_db)
):
    # 获取最新的活动列表
    result = await db.execute(
        select(Activity)
        .order_by(Activity.activity_time.desc())
        .limit(5)
    )
    activities = result.scalars().all()
    
    return PostList(
        total_page=1,
        current_page=1,
        has_next=False,
        data=activities
    )

@router.get("", response_model=PostList)
async def get_activities(
    page: int = Query(1, gt=0),
    size: int = Query(10, gt=0),
    name: Optional[str] = None,
    category_id: Optional[List[int]] = Query(None),
    organization_id: Optional[List[int]] = Query(None),
    location_id: Optional[List[int]] = Query(None),
    sort: Optional[str] = Query(None, regex="^(ID|DATE)$"),
    db: AsyncSession = Depends(get_db)
):
    query = select(Activity)
    
    # 应用过滤条件
    if name:
        query = query.filter(Activity.name.contains(name))
    if category_id:
        query = query.filter(Activity.type_id.in_(category_id))
    if location_id:
        # 这里需要根据实际的数据结构来实现位置过滤
        pass
    
    # 应用排序
    if sort == "DATE":
        query = query.order_by(Activity.activity_time.desc())
    else:
        query = query.order_by(Activity.id.desc())
    
    # 获取总数
    count_query = select(func.count()).select_from(query)
    total = await db.scalar(count_query)
    
    # 分页
    query = query.offset((page - 1) * size).limit(size)
    result = await db.execute(query)
    activities = result.scalars().all()
    
    return PostList(
        total_page=ceil(total / size),
        current_page=page,
        has_next=page * size < total,
        data=activities
    )

@router.get("/{activity_id}/detail", response_model=ActivitySchema)
async def get_activity_detail(
    activity_id: int,
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(
        select(Activity).where(Activity.id == activity_id)
    )
    activity = result.scalar_one_or_none()
    
    if not activity:
        raise DataNotFoundError()
    
    return activity

@router.get("/{activity_id}/content")
async def get_activity_content(
    activity_id: int,
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(
        select(Activity.content).where(Activity.id == activity_id)
    )
    content = result.scalar_one_or_none()
    
    if not content:
        raise DataNotFoundError()
    
    return {"code": 10000, "data": content}

@router.get("/{activity_id}/poster")
async def get_activity_poster(
    activity_id: int,
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(
        select(Activity.poster).where(Activity.id == activity_id)
    )
    poster = result.scalar_one_or_none()
    
    if not poster:
        raise DataNotFoundError()
    
    return {"code": 10000, "data": poster}

@router.post("/create", status_code=201)
async def create_activity(
    activity: ActivityCreate,
    current_user: TokenData = Depends(check_admin_permission),
    db: AsyncSession = Depends(get_db)
):
    # 检查是否已存在同名活动
    result = await db.execute(
        select(Activity).where(Activity.name == activity.name)
    )
    if result.scalar_one_or_none():
        raise DuplicatePublishError()
    
    db_activity = Activity(**activity.dict())
    db_activity.publisher_id = current_user.id
    
    db.add(db_activity)
    await db.commit()
    
    return {"code": 10000, "data": "success"} 